package cliente;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class XMLCreator {
	
	static SAXBuilder builder=new SAXBuilder();
	static File xmlFile = new File("playersdb.xml");
	static boolean repetido;
	static int filaSeleccionada;
	static String idplayer;
	
	static void meterEnTabla(){
		if(GuiCliente.modeloTablaAnadir.getRowCount()!=0){		
			for(int x=0;x<GuiCliente.modeloTablaAnadir.getRowCount();x++){	
				if(GuiCliente.modeloTablaAnadir.getValueAt(x, 0).equals(GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 0))==true){
					repetido=true;
					x=GuiCliente.modeloTablaAnadir.getRowCount()+1;
				}else{
					repetido=false;
				}
			}
			if(repetido==false){
				Object colTablaAnadir[]= {GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 0),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 1),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 2),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 3),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 4),GuiCliente.spinnerDineroCompra.getValue()};
				GuiCliente.modeloTablaAnadir.addRow(colTablaAnadir);
				repetido=true;
				XMLCreator.guardarXML();
			}
			else{
					JOptionPane.showMessageDialog(null, "ID repetida en la base de datos", "Advertencia",JOptionPane.PLAIN_MESSAGE);
				}
		}else if(repetido!=true){
			Object colTablaAnadir[]= {GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 0),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 1),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 2),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 3),GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 4),GuiCliente.spinnerDineroCompra.getValue()};
			GuiCliente.modeloTablaAnadir.addRow(colTablaAnadir);
			XMLCreator.guardarXML();
		}
	}
	
	static void guardarXML(){
		
		String id =(String) GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 0);
		String rating = (String) GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 1);
		String level = (String) GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 2);
		String name = (String) GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 3);
		String position = (String) GuiCliente.modeloTablaBuscar.getValueAt(URLReaderPlayers.setLead(), 4);
		String precio = Integer.toString((int) GuiCliente.spinnerDineroCompra.getValue());
		
		System.out.println(id);
		System.out.println(rating);
		System.out.println(level);
		System.out.println(name);
		System.out.println(position);
		System.out.println(precio);
		
		try{	
			System.out.println("paso 1");
			
			//Abrir playersdb.xml

			Document doc = (Document) builder.build(xmlFile);
			Element rootNode = doc.getRootElement();
			System.out.println("paso 2");

			Element nuevoplayer = new Element("player");
			
			nuevoplayer.setAttribute(new Attribute ("id" ,id));
			
			rootNode.addContent(nuevoplayer);

			Element playerid = new Element("id").setText(id);
			nuevoplayer.addContent(playerid);
			Element playername = new Element("name").setText(name);
			nuevoplayer.addContent(playername);
			Element playerrating = new Element("rating").setText(rating);
			nuevoplayer.addContent(playerrating);
			Element playerlevel = new Element("level").setText(level);
			nuevoplayer.addContent(playerlevel);
			Element playerposition = new Element("position").setText(position);
			nuevoplayer.addContent(playerposition);
			Element playerprecio = new Element("precio").setText(precio);
			nuevoplayer.addContent(playerprecio);
			
			List list2 = rootNode.getChildren("player");
			
			int[]indiceborrado;
			
			indiceborrado=new int[list2.size()];
			
			for (int i = 0; i < list2.size(); i++) {
				Element node = (Element) list2.get(i);
				if(node.getAttributeValue("id").equals("")==true){
					indiceborrado[i]=i;
				}
			}
			for(int x=0;x<list2.size();x++){
				if(indiceborrado[x]!=0){
					list2.remove(x);	
				}					   
			}
			
			XMLOutputter xmlOutput = new XMLOutputter();
			xmlOutput.setFormat(Format.getPrettyFormat());
			xmlOutput.output(doc, new FileWriter("playersdb.xml"));
			
		}catch(Exception b){}

	}
	
	static void cargarXML(){
		try {
			Document document =(Document) builder.build(xmlFile);
			Element rootNode = document.getRootElement();
			List list=rootNode.getChildren("player");

			for (int i = 0; i < list.size(); i++) {
			Element node = (Element) list.get(i);
			Object nuevaFila[]= {node.getChildText("id"),node.getChildText("rating"),node.getChildText("level"),node.getChildText("name"),node.getChildText("position"),node.getChildText("precio")};
			GuiCliente.modeloTablaAnadir.addRow(nuevaFila);
			}
		} catch (Exception b) {}
	}

	static void eliminarFilaBaseDatos(){
		GuiCliente.modeloTablaAnadir = (DefaultTableModel) GuiCliente.tablaAnadir.getModel();
	    filaSeleccionada = GuiCliente.tablaAnadir.getSelectedRow();
	    if (filaSeleccionada >(-1)){
	    	idplayer=(String) GuiCliente.modeloTablaAnadir.getValueAt(filaSeleccionada, 0);
	    	GuiCliente.modeloTablaAnadir.removeRow(filaSeleccionada);
	    	eliminarDeBaseDatos();
	    }
	}
	
	static void eliminarDeBaseDatos(){
	
		try{

		Document doc = (Document)builder.build(xmlFile);
		Element rootNode = doc.getRootElement();
		List list=rootNode.getChildren("player");
		
		for (int x = 0; x < list.size(); x++) {
			Element node = (Element) list.get(x);
			if(node.getAttributeValue("id").equals(idplayer)==true){
				list.remove(x);							
			}
		} 
		
		XMLOutputter xmlOutput = new XMLOutputter();
		xmlOutput.setFormat(Format.getPrettyFormat());
		xmlOutput.output(doc, new FileWriter("playersdb.xml"));

		}catch (Exception b) {}
	}
}
